package org.greatstorm.servlet;

import java.util.ArrayList;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.expressme.webwind.Config;
import org.expressme.webwind.Dispatcher;
import org.greatstorm.entity.EntityObject;
import org.greatstorm.service.AlbumManager;
import org.greatstorm.service.ArticleManager;
import org.greatstorm.service.CategoryManager;
import org.greatstorm.service.ConfigManager;
import org.greatstorm.service.TagManager;

import com.google.inject.Guice;

public class GSDispatcher extends Dispatcher {

	Logger log = Logger.getLogger(GSDispatcher.class.getName());

	ConfigManager cmanager = Guice.createInjector().getInstance(
			ConfigManager.class);

	CategoryManager catmanager = Guice.createInjector().getInstance(
			CategoryManager.class);

	AlbumManager almmanager = Guice.createInjector().getInstance(
			AlbumManager.class);

	ArticleManager amanager = Guice.createInjector().getInstance(
			ArticleManager.class);

	TagManager tagManager = Guice.createInjector()
			.getInstance(TagManager.class);

	@Override
	public void init(Config config) throws ServletException {
		super.init(config);

		// // init the timezone:
		// String timezone = config.getInitParameter("timezone");
		// if (timezone == null) {
		// timezone = "GMT+8";
		// }
		// TimeZone.setDefault(TimeZone.getTimeZone(timezone));

		// TODO: TEST destroy all data
		deteleAllData();

		// init config data
		initEntityData();

		// TODO: register json-rpc service
	}

	private void deteleAllData() {
		cmanager.deleteAll();
		catmanager.deleteAll();
		almmanager.deleteAll();
		amanager.deleteAll();
		tagManager.deleteAll();
	}

	private void initEntityData() {
		// 1. init config data
		cmanager.initData();

		// 2 init a default category
		catmanager.addCategory("Default");

		// 3 init a default album
		almmanager.addAlbum("Default", 1);

		// 2. init a smaple blog article
		EntityObject c = catmanager.getCategoryByName("Default");
		amanager.addArticle(c.getKey(), "Welcome to vvlog!",
				"This a sample article", new ArrayList<String>());
	}
}
